package com.sdx.console.video.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.video.entity.ConsultVideo;
import com.sdx.console.video.service.ConsultVideoService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


/**
 * 咨询视频 接口
 */
@RequestMapping("/consultVideo/consultVideo")
@Controller
public class ConsultVideoController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(ConsultVideoController.class);
    private static final String MODEL = "/consultVideo/consultVideo";


    @Resource
	private ConsultVideoService consultVideoService;

	@Resource
	private ResCloudFileService resCloudFileService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {

		view.addObject("videoTypeList", consultVideoService.querViodeTypes());
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("consultVideo.consultVideo.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("consultVideo.consultVideo.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer id) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        ConsultVideo consultVideo = consultVideoService.queryById(id);
        view.addObject("consultVideo", consultVideo);
		setPageParam(view,request);
		try {
			view.addObject("consultVideoJson", JacksonUtils.toJsonString(consultVideo,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("consultVideo.consultVideo.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("consultVideo.consultVideo.query")
    @ResponseBody
    public JsonResult<PageQuery> list(ConsultVideo condtion)
    {
        PageQuery page = condtion.getPageQuery();
        consultVideoService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,ConsultVideo consultVideo,HttpServletRequest request
							,MultipartFile coverFile
	) {
		log.info("编辑视频");
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/videoCover/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(coverFile)) {
			try
			{
		        String coverFileNamePair = FileUtils.upload(subPath,coverFile);
		        String coverStoreFile = coverFileNamePair.split("::")[0];
		        coverStoreFile = subPath+coverStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+coverStoreFile,bucketName,coverStoreFile.substring(1));
				String coverUrl = "https://sdxcomm."+ ConfigService.ossDomain+coverStoreFile;
				consultVideo.setCover(coverUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,coverStoreFile,coverUrl,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			consultVideo.setCreatedBy(user.getId().intValue());
			consultVideo.setCreatedName(user.getName());
			consultVideo.setCreatedTime(new Date());
			consultVideo.setUpdatedBy(user.getId().intValue());
			consultVideo.setUpdatedName(user.getName());
			consultVideo.setUpdatedTime(new Date());
			consultVideoService.save(consultVideo);
		} else {
			consultVideo.setUpdatedBy(user.getId().intValue());
			consultVideo.setUpdatedName(user.getName());
			consultVideo.setUpdatedTime(new Date());
			consultVideoService.updateTemplate(consultVideo);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("consultVideo.consultVideo.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)ConsultVideo consultVideo,HttpServletRequest request
							,@RequestParam("coverFile") MultipartFile coverFile
		)
    {

        return save(true,consultVideo,request
					,coverFile
		);
    }

    @PostMapping("/update.json")
    @Function("consultVideo.consultVideo.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  ConsultVideo consultVideo,HttpServletRequest request
							,@RequestParam("coverFile")MultipartFile coverFile
		) {
		return save(false,consultVideo,request
		,coverFile
		);
    }



    @GetMapping("/view.json")
    @Function("consultVideo.consultVideo.query")
    @ResponseBody
    public JsonResult<ConsultVideo>queryInfo(Integer id) {
        ConsultVideo consultVideo = consultVideoService.queryById( id);
        return  JsonResult.success(consultVideo);
    }

    @PostMapping("/delete.json")
    @Function("consultVideo.consultVideo.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        consultVideoService.batchDelConsultVideo(idList);
        return JsonResult.success();
    }


}
